//
//  Post1ViewController.m
//  PostScreens
//
//  Created by dongmh on 4/22/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SpendFunkAppDelegate.h"
#import "Post1ViewController.h"
#import "Post2ViewController.h"
#import "image.h"
#import "CategoryViewController.h"
#import "Global.h"

NSMutableDictionary *SpendInfo;
@implementation Post1ViewController

-(id)init
{
	//NSMutableDictionary *SpendInfo = nil;
	return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	[self initView];
}

- (void)initView
{
	NSString *path = nil;
	UIImage *img = nil;
	
	// Header
	path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	img  = [UIImage imageNamed:path];
	UIImageView *imgvHeader = [[UIImageView alloc] initWithFrame:CGRectMake(0, -20,  img.size.width, img.size.height)];
	[imgvHeader setImage:img];
	[self.view addSubview:imgvHeader];
	[imgvHeader setUserInteractionEnabled:YES];
	[imgvHeader release];
	
	// Back button
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, -15, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onClickBack) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnBack];
	
	// Background for post1 screen
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 25, img.size.width , img.size.height)];
	[imgvBkgr setImage:img];
	[self.view addSubview:imgvBkgr];
	[imgvBkgr setUserInteractionEnabled:YES];
	[imgvBkgr release];
	[path release];
	
	
	// Table view
	m_pTablePost1 = [[UITableView alloc] initWithFrame:CGRectMake(5, 35, 310, 150) style:UITableViewStyleGrouped];
	[self.view addSubview:m_pTablePost1];
	[m_pTablePost1 setBackgroundColor:[UIColor clearColor]];
	m_pTablePost1.scrollEnabled = NO;
	m_pTablePost1.delegate = self;
	m_pTablePost1.dataSource =self;
	
	// Next button
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN];
	img = [UIImage imageNamed:path];
	m_pBtnNext = [[UIButton alloc] initWithFrame:CGRectMake(320/2 - img.size.width/2, 200, img.size.width, img.size.height)];
	[m_pBtnNext setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnNext setTitle:@"Next" forState:UIControlStateNormal];
	[m_pBtnNext setBackgroundColor:[UIColor clearColor]];
	m_pBtnNext.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnNext addTarget:nil action:@selector(onClickNext) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnNext];
	// Please wait ... 
	_blockerView = [[[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)] autorelease];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 0.0;
	_blockerView.clipsToBounds = YES;
	if ([_blockerView.layer respondsToSelector: @selector(setCornerRadius:)]) [(id) _blockerView.layer setCornerRadius: 10];
	
	UILabel	*label = [[[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)] autorelease];
	label.text = NSLocalizedString(@"Please Wait…", nil);
	label.backgroundColor = [UIColor clearColor];
	label.textColor = [UIColor whiteColor];
	label.textAlignment = UITextAlignmentCenter;
	label.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label];
	
	UIActivityIndicatorView				*spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite] autorelease];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
	[self.view addSubview: _blockerView];
	[spinner startAnimating];
	
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 40.0;
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//	[tableView deselectRowAtIndexPath:indexPath animated:YES];
//}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
	return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}
	
	UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",IMG_BTN_ARROW]]];
	cell.accessoryView = imageView;
	switch (indexPath.row) {
		case 0:
			cell.textLabel.text = @"Price";
			break;
		case 1:
			cell.textLabel.text = @"Where";
			break;
		case 2:
			cell.textLabel.text = @"Categories";
			break;
		default:
			break;
	}
	return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	return 1;
}
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	switch (indexPath.row) {
		case 0:
			// Price
			//rowSlected = 0;
			[g_AppDelegate openPriceView];
			break;
			// Where
		case 1:
			_blockerView.alpha = 1.0;
			g_iMode = MODE_WHERE;
			[self getNearbyPlaceWithgeoLat:1.23 andGeoLong:103.43];
			break;
			// Category
		case 2:
			_blockerView.alpha =1.0;
			g_iMode = MODE_CATE;
			[self getAllCateWithlimit:10 offset:0];

			break;
	}
}
#pragma mark getNearbyPlaceWithgeoLatandgeoLong
- (void)getNearbyPlaceWithgeoLat:(double)lat andGeoLong:(double)lng{
	if (m_pFoursquare) {
		[m_pFoursquare release];
		m_pFoursquare = nil;
	}
	m_pFoursquare = [[Foursquare alloc] init];
	if ([[Foursquare sharedInstance] loginWithUsername:@"dongmh.dce.hut@gmail.com" password:@"h4yl4chjnhmjnh"] || [[Foursquare sharedInstance] isActive]) {
		NSLog(@"login success forsquare!");
		m_pArrNearbyPlaces = [[NSArray alloc] init];
		m_pArrNearbyPlaces = [[Foursquare sharedInstance] findLocationsNearbyLatitude:lat longitude:lng limit:30 searchterm:nil];
		_blockerView.alpha = 0.0;
		[g_AppDelegate openWhereViewWithArrPlaces:m_pArrNearbyPlaces];
	}else {
		_blockerView.alpha = 0.0;
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Have an error" message:@"Please try again later!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	[m_pFoursquare logout];
}
#pragma mark getAllCate
- (void)getAllCateWithlimit:(int)limit offset:(int)offset{
	
	NSString *post = [[NSString alloc] initWithFormat:@"limit=%@&offset=%@",[NSString stringWithFormat:@"%i",limit],[NSString stringWithFormat:@"%i",offset]];
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/category/getallcategory"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
		
		if(!m_pArrCate){
			m_pArrCate = [[NSMutableArray alloc] init];
		}else {
			[m_pArrCate removeAllObjects];
		}
	}
	else
	{
		
	}
	
}
-(void)onClickBack
{
	[g_AppDelegate openFeedView];
}

-(void)onClickNext{
	//NSString *cateid = [[pDicPost1Infor objectForKey:@"cate"] valueForKey:kCateID];
//	NSString *ttle = [NSString stringWithString:@"ttle"];
//	int amount = 9;
//	UIImage *img = [UIImage imageNamed:@""];
//	NSString *location = [pDicPost1Infor objectForKey:location];
	
	//_blockerView.alpha =1.0;
//	g_iMode = MODE_ADDSPEND;
//	[self addSpendwithCateid:@"2" userid:@"9" titleSpend:@"title" amount:9 picture:@"" location:@"Ha noi viet nam"];
	
	
	if (![SpendInfo valueForKey:@"kPlace"] || ![SpendInfo valueForKey:kCateID] || ![SpendInfo valueForKey:@"kMount"]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please add full information!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}else {
		[g_AppDelegate onClickToPost2];
	}

	
}
- (void)addSpendwithCateid:(NSString*)cateid userid:(NSString*)userid titleSpend:(NSString*)ttle amount:(int)amount picture:(UIImage*)img location:(NSString*)location{
	
	
	
	NSString *post = [[NSString alloc] initWithFormat:@"cate_id=%@&userid=%@&title=%@&amount=%@&picture=%@&location=%@",cateid,userid,ttle,[NSString stringWithFormat:@"%i",amount],@"",location];
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/spend/addspend"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
		
	}
	else
	{
		
	}
}
#pragma mark connect delegate
#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSString *a = [[NSString alloc] initWithData:loginStatus encoding:NSUTF8StringEncoding];
	NSLog(@"%@",a);
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		_blockerView.alpha =0.0;
		NSLog(@"No Errors");
		if (g_iMode == MODE_CATE) {
			[g_AppDelegate openCateWithArrCate:m_pArrCate];
		}
	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	[connection release];
	[m_pWebData release];
}

#pragma mark xmlParser delegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
	if (g_iMode == MODE_CATE) {
		if([currentElement isEqualToString:kCateID]){
			iCountCate++;
			if(iCountCate >=2){
				[m_pArrCate addObject:m_pDicCateInfo];
			}
			[m_pDicCateInfo release];
			m_pDicCateInfo = nil;
			m_pDicCateInfo = [[NSMutableDictionary alloc] init];
		}
		
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
	if (g_iMode == MODE_CATE) {
		// where
		if([currentElement isEqualToString:kCateID]){
			[m_pDicCateInfo setObject:string forKey:kCateID];
		}
		if([currentElement isEqualToString:kCateName]){
			[m_pDicCateInfo setObject:string forKey:kCateName];
		}
	}
	if (g_iMode == MODE_ADDSPEND) {
		// addspend
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	NSLog(@"%@",elementName);
	
	[currentElementValue release];
	currentElementValue = nil;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
